package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.server.vo.SoundVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SoundService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PicUploadService picUploadService;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    /**
     * 发送传音
     * @param soundFile
     * @return
     */
    public boolean saveSound(MultipartFile soundFile) {
        User user = UserThreadLocal.get();

        if (null == user){
            return false;
        }

        //创建redis语音键(传音只能10次)
        //在redis里设置一个唯一的缓存键，根据当天的时间设置，并且根据下面的清除缓存设置清除
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        String key = user.getId() + "_" + dateTime + "_SEND_SOUND";

        //判断
        String keyValue = redisTemplate.opsForValue().get(key);
        if (null == keyValue) {
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (keyValue.equals("0")) {
            return false;
        } else {
            redisTemplate.opsForValue().decrement(key);
        }


        //填充信息
        Sound sound = new Sound();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());
        sound.setUserId(user.getId());
        sound.setGender(userInfo.getSex().name());

        try {
            //把录音上传到oss, 并保存到Mongodb
            PicUploadResult picUploadResult = this.picUploadService.upload(soundFile);
            sound.setSoundUrl(picUploadResult.getName());   //录音路径

            //设置url
            //sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

            this.soundApi.saveSound(sound);
            return true;

        } catch (Exception e) {
            log.error("发布传音失败！file = " + soundFile.getOriginalFilename() , e);
        }
        return true;
    }

    /**
     * 接收传音
     * @return
     */
    public SoundVo querySound() {
        User user = UserThreadLocal.get();

        //判断他的接收次数
        //创建redis键(接收传音每天只能10次)
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        //记当天的接收次数
        String key = user.getId() + "_" + dateTime + "_GET_SOUND";

        //判断
        String keyValue = redisTemplate.opsForValue().get(key);
        if (null == keyValue) {
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (keyValue.equals("0")) {
            return null;
        } else {
            redisTemplate.opsForValue().decrement(key);
        }

        //获取到所有人声音文件的集合
        List<Sound> sounds = soundApi.querySounds();
        //通过createSoundUserId方法，传入sounds和当前用户的对象，随机获取非当前用户的传音
        Sound sound = createSoundUserId(sounds, userInfoService.queryUserInfoByUserId(user.getId()));
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(sound.getUserId());

        //封装数据
        SoundVo soundVo = new SoundVo();
        soundVo.setUserId(sound.getUserId());
        soundVo.setAge(userInfo.getAge());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setNickname(userInfo.getNickName());

        soundVo.setGender(userInfo.getSex().name().toLowerCase());
        //剩余接收录音的次数
        int count = Integer.parseInt(redisTemplate.opsForValue().get(key));
        soundVo.setRemainingTimes(count);   //TODO
        soundVo.setSoundUrl(sound.getSoundUrl());

        return soundVo;
    }

    /**
     * 随机获取非当前用户的传音
     * 排除自己的和已获取过的
     *
     * @param sounds
     * @param userInfo
     * @return
     */
    private Sound createSoundUserId(List<Sound> sounds, UserInfo userInfo) {
        //获得任意一个sound声音对象
        Sound sound = sounds.get(RandomUtils.nextInt(0, sounds.size() - 1));
        /*QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",sound.getUserId());
        UserInfo soundUser = this.userInfoMapper.selectOne(queryWrapper);*/
        //UserInfo soundUser = userInfoMapper.selectById(sound.getUserId());
        //递归判断,非自己,异性,不重复
        if (sound.getUserId() == userInfo.getUserId()
                || sound.getGender().equals(userInfo.getSex().name())) {
            if(redisTemplate.opsForHash().hasKey("sound", sound.getSoundUrl())==null){
                redisTemplate.opsForHash().put("sound", sound.getSoundUrl(), "0");
                return sound;
            }else if(redisTemplate.opsForHash().hasKey("sound", sound.getSoundUrl())){
                createSoundUserId(sounds, userInfo);
            }
        }
        redisTemplate.opsForHash().put("sound", sound.getSoundUrl(), "0");
        return sound;
    }
}
